package uit.uthuoc.fragment;

import java.util.ArrayList;

import uit.uthuoc.dal.DrugDAO;

import com.uit.uthuoc.R;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ListView;

public abstract class BaseSearchableFragment extends ListFragment{
	
	private static final String LOG_ID = "uit.uthuoc.fragment.BaseSearchableFragment";
	
    protected SearchView mSearchView;
	protected SearchResultFragmentInterface parentActivity;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		DrugDAO.setContext(getActivity());
		iniListAdapter();
	}
	
	

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
	    // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            parentActivity = (SearchResultFragmentInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement SearchResultFragmentInterface");
        }

	}

	
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
	}


	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
        // Inflate the menu; this adds items to the action bar if it is present.
        inflater.inflate(R.menu.main_activity_actions, menu);
        
        MenuItem searchItem = menu.findItem(R.id.action_search);
        
        mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setQueryHint(getString(R.string.search_hint));
        setQueryListener();
        
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// Get DTO ID by position
		int drugId = position;
		
		//
		parentActivity.onListItemClickListener(drugId);
	}
	protected abstract void setQueryListener();
	protected abstract void iniListAdapter();

}
